﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
using BotvaBot.RequestChainItems;
using Castle.Core;
using Helpers;

namespace BotvaBot.BusinessLayer.RequestChainItems.Factory
{
    public class BotvaChineItemFactory
    {
        protected static readonly LifestyleType Lifestyle = LifestyleType.Transient;


        static BotvaChineItemFactory()
        {
            Init();
        }

        public static IBotvaChainItem Get(string key)
        {
            return Resolver.Resolve<IBotvaChainItem>(key);
        }



        protected static WindsorContainer Resolver { get; set; }
        
        protected static void Init()
        {
            Resolver = new WindsorContainer();

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes();
                foreach (var type in types)
                {
                    if (ReflectionHelper.HasAttribute<ChainItemAttribute>(type, false))
                    {
                        Register(type);
                    }
                }
            }
        }

        protected static void Register(Type type)
        {
            Resolver.AddComponentLifeStyle(GetFullName(type), typeof(IBotvaChainItem), type, Lifestyle);
        }

        protected static void Register<T>()
            where T : class
        {
            Resolver.AddComponentLifeStyle<IBotvaChainItem, T>(GetFullName(typeof(T)), Lifestyle);
        }

        protected static string GetFullName(Type type)
        {
            //return string.Format("{0}:{1}.{2}", type.Assembly.GetName().Name, type.Namespace, type.Name);
            return type.Name;
        }
    }
}
